package com.antis.olsl.data.turnover;

import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.antis.olsl.arouterlib.DataRoutePath;
import com.antis.olsl.base.BaseActivity;
import com.antis.olsl.base.utils.LogUtils;
import com.antis.olsl.base.utils.ToastUtil;
import com.antis.olsl.data.R;
import com.antis.olsl.data.adapter.PosTurnoverAdapter;
import com.antis.olsl.data.databinding.ActivityPosTurnoverBinding;
import com.antis.olsl.data.response.GetPosTurnoverResp;
import com.antis.olsl.library.dialog.ChooseDateDialog;
import com.antis.olsl.library.dialog.ChooseSalesroomDialog;
import com.antis.olsl.library.response.SalesroomOrWarehouseInfo;
import com.antis.olsl.library.widget.ChooseSalesroomView;
import com.antis.olsl.library.widget.MyInputSearchLayout;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.MPPointF;
import com.trello.rxlifecycle2.LifecycleTransformer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

@Route(path = DataRoutePath.ACTIVITY_POS_TURNOVER)
public class PosTurnoverActivity extends BaseActivity<ActivityPosTurnoverBinding> implements OnChartValueSelectedListener, PosTurnoverContract.View, ChooseSalesroomView.ChooseSalesroomListener, MyInputSearchLayout.TextChangedListener, ChooseSalesroomDialog.ChooseSalesroomListener, ChooseDateDialog.ChooseDateListener {

    private String searchText = "";
    private int pageNum = 0;
    private boolean isEnd;
    private PosTurnoverAdapter mAdapter;
    private List<GetPosTurnoverResp.ContentBean.PosListBean> mList = new ArrayList<>();

    private PosTurnoverPresenter mPresenter;

    private SimpleDateFormat textDateFormat = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());

    private ChooseDateDialog chooseDateDialog;
    private Date startDate;
    private Date endDate;

    private ChooseSalesroomDialog chooseSalesroomDialog;
    private String salesRoomIds = "";
    private SalesroomOrWarehouseInfo mInfo;
    private ArrayList<SalesroomOrWarehouseInfo> salesroomInfos = new ArrayList<>();
    private ArrayList<SalesroomOrWarehouseInfo> selectedSalesroomInfos = new ArrayList<>();

    @Override
    protected ActivityPosTurnoverBinding getViewBinding() {
        return ActivityPosTurnoverBinding.inflate(getLayoutInflater(), baseBinding.getRoot(), true);
    }

    @Override
    protected void initPresenter() {
        super.initPresenter();
        mPresenter = new PosTurnoverPresenter();
        mPresenter.takeView(this);
    }

    @Override
    protected void initViews() {
        viewBinding.layoutChooseSalesroom.chooseSalesroomView.setSalesroomInfos(null);
        viewBinding.layoutChooseSalesroom.chooseSalesroomView.setChooseSalesroomListener(this);
        initChart();

        viewBinding.layoutSearchInput.myInputSearchLayout.setHintText("请输入POS流水号");
        viewBinding.layoutSearchInput.myInputSearchLayout.setListener(this);

        initDate();

        mAdapter = new PosTurnoverAdapter(R.layout.item_pos_turnover, mList);
        viewBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        viewBinding.recyclerView.setAdapter(mAdapter);

        viewBinding.rlChooseDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // chooseDateDialog = new ChooseDateDialog(PosTurnoverActivity.this, "选择时间", startDate, PosTurnoverActivity.this, "startDate");
                ARouter.getInstance()
                        .build(DataRoutePath.ACTIVITY_POS_TURNOVER_DETAIL)
                        .withString("posNumber", "123")
                        .navigation();
            }
        });

        mAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                viewBinding.recyclerView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (isEnd) {
                            mAdapter.getLoadMoreModule().loadMoreEnd();
                        } else {
                            flushData();
                        }
                    }
                }, 200);
            }
        });

        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

            }
        });
    }

    private void initChart() {
        viewBinding.chartTotalAmount.setUsePercentValues(true);
        viewBinding.chartTotalAmount.getDescription().setEnabled(false);
        viewBinding.chartTotalAmount.setExtraOffsets(5, 5, 5, 5);

        viewBinding.chartTotalAmount.setDragDecelerationFrictionCoef(0.95f);
        viewBinding.chartTotalAmount.setCenterTextSize(18);

        viewBinding.chartTotalAmount.setDrawHoleEnabled(true);
        viewBinding.chartTotalAmount.setHoleColor(Color.WHITE);

        viewBinding.chartTotalAmount.setTransparentCircleColor(Color.WHITE);
        viewBinding.chartTotalAmount.setTransparentCircleAlpha(110);

        viewBinding.chartTotalAmount.setHoleRadius(85f);
        viewBinding.chartTotalAmount.setTransparentCircleRadius(30f);

        viewBinding.chartTotalAmount.setDrawCenterText(true);

        viewBinding.chartTotalAmount.setRotationAngle(0);
        // enable rotation of the chart by touch
        viewBinding.chartTotalAmount.setRotationEnabled(true);
        viewBinding.chartTotalAmount.setHighlightPerTapEnabled(true);

        // chart.setUnit(" €");
        // chart.setDrawUnitsInChart(true);

        // add a selection listener
        viewBinding.chartTotalAmount.setOnChartValueSelectedListener(this);

        viewBinding.chartTotalAmount.animateY(1400, Easing.EasingOption.EaseInOutQuad);
        // chart.spin(2000, 0, 360);

        Legend legend = viewBinding.chartTotalAmount.getLegend();
        legend.setEnabled(false);

        // entry label styling
        viewBinding.chartTotalAmount.setDrawEntryLabels(false);
        viewBinding.chartTotalAmount.setEntryLabelColor(Color.WHITE);
        viewBinding.chartTotalAmount.setEntryLabelTextSize(12f);
    }

    private void initDate() {
        Calendar calendar = Calendar.getInstance();

        endDate = new Date();
        calendar.setTime(endDate);
        //初始进来查询近7天的数据
        calendar.add(Calendar.DATE, -7);
        startDate = calendar.getTime();
        setDateText();

        flushData();
    }

    private void setDateText() {
        String date = textDateFormat.format(startDate) + "-" + textDateFormat.format(endDate);
        viewBinding.tvDate.setText(date);
    }

    private void flushData() {
        Map<String, Object> map = new HashMap<>();
        map.put("shopId", salesRoomIds);
        map.put("startTime", dateFormat.format(startDate));
        map.put("endTime", dateFormat.format(endDate));
        map.put("keyword", searchText);
        map.put("pageNum", pageNum);
        map.put("pageSize", 10);
        mPresenter.getPosTurnover(map);
    }

    @Override
    protected void initData() throws IllegalAccessException {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mPresenter) {
            mPresenter.unSubscribe();
        }

        if (null != chooseDateDialog) {
            chooseDateDialog.dismiss();
        }

        if (null != chooseSalesroomDialog) {
            chooseSalesroomDialog.dismiss();
        }
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }

    @Override
    public void getSalesroomInfoListSuccess(List<SalesroomOrWarehouseInfo> list) {
        salesroomInfos.clear();
        salesroomInfos.addAll(list);
        LogUtils.e("getSalesroomInfoListSuccess resp= " + list.size());

        chooseSalesroomDialog = new ChooseSalesroomDialog(this, salesroomInfos, this);
    }

    @Override
    public void getSalesroomInfoListFailure(String msg) {
        LogUtils.e("getSalesroomInfoListFailure msg= " + msg);
        if (TextUtils.isEmpty(msg)) {
            msg = "请求失败,请稍后重试";
        }
        ToastUtil.showToast(this, msg);
    }

    @Override
    public void getPosTurnoverSuccess(GetPosTurnoverResp.ContentBean bean) {
        setData(bean);

        if (pageNum == 0) {
            mList.clear();
        }
        if (null == bean.posList) {
            return;
        }
        mList.addAll(bean.posList);
        if (bean.posList.size() >= 10) {
            isEnd = false;
            pageNum += 1;
        } else {
            isEnd = true;
        }
        viewBinding.recyclerView.setAdapter(mAdapter);
        mAdapter.setList(mList);
        mAdapter.getLoadMoreModule().loadMoreComplete();
    }

    private void setData(GetPosTurnoverResp.ContentBean bean) {
        GetPosTurnoverResp.ContentBean.QuotaInfoBean info = bean.quotaInfo;
        if (null == info) {
            return;
        }
        viewBinding.chartTotalAmount.setCenterText("总额度\n\r\n\r" + info.totalAmount);
        float bankCardQuota = info.bankCardQuota;
        float weChatQuota = info.weChatQuota;
        float alipayQuota = info.alipayQuota;
        float couponQuota = info.couponQuota;
        float cashQuota = info.cashQuota;

        ArrayList<PieEntry> entries = new ArrayList<>();
        // NOTE: The order of the entries when being added to the entries array determines their position around the center of
        // the chart.
        entries.add(new PieEntry(bankCardQuota, "银行卡", null));
        entries.add(new PieEntry(weChatQuota, "微信", null));
        entries.add(new PieEntry(alipayQuota, "支付宝", null));
        entries.add(new PieEntry(couponQuota, "优惠券", null));
        entries.add(new PieEntry(cashQuota, "现金", null));

        PieDataSet dataSet = new PieDataSet(entries, "Election Results");

        dataSet.setDrawIcons(false);

        dataSet.setSliceSpace(0);
        dataSet.setIconsOffset(new MPPointF(0, 40));
        dataSet.setSelectionShift(10f);

        dataSet.setDrawValues(false);

        // add a lot of colors

        ArrayList<Integer> colors = new ArrayList<>();
        colors.add(Color.rgb(255, 167, 0));
        colors.add(Color.rgb(0, 162, 154));
        colors.add(Color.rgb(27, 163, 248));
        colors.add(Color.rgb(237, 87, 87));
        colors.add(Color.rgb(163, 171, 181));

        dataSet.setColors(colors);

        PieData data = new PieData(dataSet);
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);
        viewBinding.chartTotalAmount.setData(data);

        // undo all highlights
        viewBinding.chartTotalAmount.highlightValues(null);

        viewBinding.chartTotalAmount.invalidate();
    }

    @Override
    public void getPosTurnoverFailure(String msg) {
        LogUtils.e("getPosTurnoverFailure msg= " + msg);
        if (TextUtils.isEmpty(msg)) {
            msg = "请求失败,请稍后重试";
        }
        ToastUtil.showToast(this, msg);
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.bindToLifecycle();
    }

    @Override
    public void clickChooseListener() {
        if (salesroomInfos == null || salesroomInfos.size() == 0) {
            getSalesroom();
        } else {
            chooseSalesroomDialog = new ChooseSalesroomDialog(this, salesroomInfos, PosTurnoverActivity.this);
        }
    }

    private void getSalesroom() {
        HashMap<String, Object> map = new HashMap<>();
        mPresenter.getSalesroomInfoList(map);
    }

    @Override
    public void clickPhone(String phone) {

    }

    @Override
    public void onTextChangeListener(String text) {
        pageNum = 0;
        searchText = text;
        flushData();
    }

    @Override
    public void onChooseSalesroomListener(boolean isChooseAll, ArrayList<SalesroomOrWarehouseInfo> choosedFiledInfos, ArrayList<SalesroomOrWarehouseInfo> sourceInofs, int selectedIndex) {
        salesroomInfos = sourceInofs;
        selectedSalesroomInfos = choosedFiledInfos;
        if (selectedIndex == -1) {
            salesRoomIds = "";
            viewBinding.layoutChooseSalesroom.chooseSalesroomView.setSalesroomInfos(null);
        } else {
            salesRoomIds = filterIds();
        }
        pageNum = 0;
        flushData();
    }

    private String filterIds() {
        ArrayList<SalesroomOrWarehouseInfo> infos = salesroomInfos;
        String name = "";
        String ids = "";
        for (int i = 0; i < infos.size(); i++) {
            ids += TextUtils.isEmpty(ids) ? infos.get(i).getId() : "," + infos.get(i).getId();
            name += TextUtils.isEmpty(name) ? infos.get(i).getName() : "," + infos.get(i).getName();
        }

        if (infos.size() > 0) {
            mInfo = infos.get(0);
        }
        viewBinding.layoutChooseSalesroom.chooseSalesroomView.setSalesroomInfos(infos);
        return ids;
    }

    @Override
    public void getDateListener(String tag, int year, int quarter, int month, int week, int day) {
        Date tmpDate = new Date();
        try {
            tmpDate = simpleDateFormat.parse(year + "-" + month + "-" + day);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (tmpDate.getTime() - System.currentTimeMillis() > 0) {
            ToastUtil.showToast(this, "选择时间不能超过当前时间");
            return;
        }
        if ("startDate".equals(tag)) {
            startDate = tmpDate;
            chooseDateDialog.dismiss();
            chooseDateDialog = new ChooseDateDialog(this, "选择结束时间", endDate, this, "endDate");
        } else {
            if (tmpDate.getTime() - startDate.getTime() < 0) {
                ToastUtil.showToast(this, "结束时间必须大于开始时间");
                return;
            }
            endDate = tmpDate;
            chooseDateDialog.dismiss();
            pageNum = 0;
            flushData();
        }
        setDateText();
    }
}